<script setup>
	import { Empty, Modal } from 'ant-design-vue'
	import dashboardCategorizeApi from '@/views/plugin/dashboard/api/dashboardCategorizeApi'
	import { isEmpty } from 'lodash-es'
	import { nextTick } from 'vue'
	import DashboardCategorizeForm from './DashboardCategorizeForm.vue'
	import DashboardGrantPermissionForm from './DashboardGrantPermissionForm.vue'
	import { designStore } from '@/views/plugin/dashboard/store/design'

	const cardLoading = ref(true)
	const emits = defineEmits(['treeSelect'])
	// 默认展开的节点
	const defaultExpandedKeys = ref([])
	const treeData = ref([])
	// 替换treeNode 中 title,key,children
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }

	const dashboardCategorizeFormRef = ref(null)
	const dashboardGrantPermissionFormRef = ref(null)
	// 当前选中的节点
	const selectedNode = ref(null)
	// 当前编辑的节点
	const editingNode = ref(null)
	// 编辑时的临时名称
	const editingName = ref('')

	// 显示添加抽屉
	const showDrawer = () => {
		selectedNode.value = null
		dashboardCategorizeFormRef.value.open()
	}

	// 开始编辑节点名称
	const startEdit = (event, node) => {
		// 阻止事件冒泡
		if (event) {
			event.stopPropagation()
		}
		if (node.id === '0') return
		editingNode.value = node
		editingName.value = node.name
	}

	// 保存编辑的名称
	const saveEdit = () => {
		if (!editingNode.value || !editingName.value.trim()) {
			editingNode.value = null
			return
		}
		const updatedData = {
			id: editingNode.value.id,
			name: editingName.value.trim(),
			parentId: editingNode.value.parentId
		}
		dashboardCategorizeApi.edit(updatedData).then(() => {
			treeData.value = []
			loadTreeData()
			editingNode.value = null
		})
	}

	// 处理拖拽结束事件
	const onDrop = (info) => {
		const dropKey = info.node.id
		const dragKey = info.dragNode.id
		if (dragKey === '0' || dropKey === dragKey) return

		// 判断是否为第三级节点
		const isTargetThirdLevel = !info.node.children && info.node.parentId !== '0'
		if (isTargetThirdLevel) return

		const updatedData = {
			id: dragKey,
			name: info.dragNode.name,
			parentId: info.dropToGap ? info.node.parentId : dropKey
		}
		dashboardCategorizeApi.edit(updatedData).then(() => {
			treeData.value = []
			loadTreeData()
		})
	}

	// 处理删除
	const handleDelete = (data) => {
		if (data) {
			dashboardCategorizeApi.delete([{ id: data.id }]).then(() => {
				treeData.value = []
				loadTreeData()
			})
		}
	}

	// 点击树查询
	const treeSelect = (selectedKeys, info) => {
		// 判断是否为第三级节点
		const isThirdLevel = !info.node.children && info.node.parentId !== '0'
		if (isThirdLevel) {
			// 更新store中的当前分类ID
			designStore().setCurrentCategoryId(info.node.id)
			// 通过事件发射通知父组件获取仪表盘详情
			// emits('treeSelect', info.node.id)
		}
	}

	// 加载左侧的树
	const loadTreeData = () => {
		dashboardCategorizeApi
			.tree()
			.then((res) => {
				cardLoading.value = false
				if (res !== null) {
					// 清空现有树数据
					treeData.value = []
					nextTick(() => {
						// 对每一层级的节点按updateTime倒序排序
						const sortTreeNodes = (nodes) => {
							if (!nodes) return nodes
							nodes.sort((a, b) => new Date(b.updateTime) - new Date(a.updateTime))
							nodes.forEach(node => {
								if (node.children) {
									node.children = sortTreeNodes(node.children)
								}
							})
							return nodes
						}
						// 对返回的数据进行排序
						res = sortTreeNodes(res)
						// 构建一级树
						treeData.value.push({
							id: '0',
							name: '仪表盘分类',
							parentId: '0',
							children: res
						})
						// 支持多个树结构的情况
						if (isEmpty(defaultExpandedKeys.value)) {
							// 默认展开3级
							treeData.value.forEach((item) => {
								// 因为0的顶级
								if (item.parentId === '0') {
									defaultExpandedKeys.value.push(item.id)
									// 取到下级ID
									if (item.children) {
										item.children.forEach((items) => {
											defaultExpandedKeys.value.push(items.id)
											// 取到三级ID
											if (items.children) {
												items.children.forEach((subItems) => {
													defaultExpandedKeys.value.push(subItems.id)
												})
											}
										})
									}
								}
							})
						}
					})
				}
			})
			.finally(() => {
				cardLoading.value = false
			})
	}

	onMounted(() => {
		loadTreeData()
	})
</script>

<template>
	<div>
		<a-card :bordered="false" :loading="cardLoading" class="left-tree-container">
			<a-tree
				v-if="treeData.length > 0"
				v-model:expandedKeys="defaultExpandedKeys"
				:tree-data="treeData"
				show-icon
				:field-names="treeFieldNames"
				@select="treeSelect"
				draggable
				@drop="onDrop"
			>
				<template #title="{ dataRef }">
					<div class="w-full" @mouseenter="selectedNode = dataRef" @mouseleave="selectedNode = null">
						<div class="flex items-center justify-between" v-if="dataRef.id === '0'">
							<div class="flex items-center">
								<FolderTwoTone v-if="dataRef.parentId === '0'" />
								<FileTwoTone v-if="dataRef.parentId !== '0'" />
								<div class="ml-2 truncate">{{ dataRef.name }}</div>
							</div>
							<div
								v-if="selectedNode && selectedNode.id === dataRef.id"
								class="flex items-center gap-2 justify-end ml-4"
							>
								<div
									v-if="!(!dataRef.children && dataRef.parentId !== '0')"
									class="cursor-pointer text-blue-500 hover:text-blue-600 flex items-center text-sm"
									@click="(e) => showDrawer(e, null)"
								>
									<PlusOutlined class="mr-1" />
								</div>
							</div>
						</div>

						<div v-else>
							<div class="flex items-center justify-between">
								<div class="flex items-center flex-1">
									<FolderTwoTone v-if="dataRef.parentId === '0'" />
									<FileTwoTone v-if="dataRef.parentId !== '0'" />
									<div v-if="editingNode?.id === dataRef.id" class="ml-2 flex-1">
										<a-input
											v-model:value="editingName"
											@pressEnter="saveEdit"
											@blur="saveEdit"
											class="edit-input"
											ref="inputRef"
										/>
									</div>
									<div v-else class="ml-2 truncate cursor-pointer">
										{{ dataRef.name }}
									</div>
								</div>

								<div
									v-if="selectedNode && selectedNode.id === dataRef.id"
									class="flex items-center gap-2 justify-end ml-2"
								>
									<div
										v-if="!(!dataRef.children && dataRef.parentId !== '0')"
										class="cursor-pointer text-blue-500 hover:text-blue-600 flex items-center text-sm"
										@click="(e) => showDrawer(e, null)"
									>
										<PlusOutlined class="mr-1" />
									</div>
									<div
										class="cursor-pointer text-blue-500 hover:text-blue-600 flex items-center text-sm"
										@click="(e) => startEdit(e, dataRef)"
									>
										<EditOutlined class="mr-1" />
									</div>
									<div
										class="cursor-pointer text-red-500 hover:text-red-600 flex items-center text-sm"
										@click="
											(e1) => {
												Modal.confirm({
													title: '确认删除',
													content: '是否确认删除该仪表盘分类？删除后数据不可恢复！',
													okText: '确认',
													cancelText: '取消',
													onOk: () => handleDelete(dataRef)
												})
												// 阻止事件冒泡
												e1.stopPropagation()
											}
										"
									>
										<DeleteOutlined class="mr-1" />
									</div>
								</div>
							</div>
						</div>
					</div>
				</template>
			</a-tree>
			<div v-else class="flex flex-col items-center">
				<a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" />
				<a-button type="primary" class="mt-4" @click="showDrawer">
					<PlusOutlined />
					添加仪表盘分类
				</a-button>
			</div>
			<DashboardCategorizeForm
				ref="dashboardCategorizeFormRef"
				@success="
					() => {
						treeData.value = []
						loadTreeData()
					}
				"
			/>
		</a-card>
	</div>
</template>

<style scoped lang="less">
	:deep(.ant-card-body) {
		padding: 14px;
	}
</style>
